<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { 
  getUsersApi, 
  createUserApi, 
  updateUserApi, 
  deleteUserApi, 
  resetUserPasswordApi 
} from '@/common/apis/users'
import type { UserItem, ResetPasswordRequestData } from '@/common/apis/users/type'
import { formatDateTime } from '@/common/utils/datetime'
import { useTable } from '@/common/composables/useTable'
import { useFormRules } from '@/common/composables/useFormRules'
import { useExport } from '@/common/composables/useExport'
import SearchInput from '@/common/components/SearchInput/index.vue'
import Pagination from '@/common/components/Pagination/index.vue'
import { Download, ArrowDown } from '@element-plus/icons-vue'

defineOptions({
  name: 'UserManagement'
})

// 搜索查询
const searchQuery = ref('')

// 导出功能
const { isExporting, exportToCSV, exportToExcel } = useExport()

// 使用表格 Composable
const {
  loading,
  tableData: userList,
  currentPage,
  pageSize,
  total,
  dialogVisible,
  dialogTitle,
  isEdit,
  currentItem: currentUser,
  fetchData: fetchUsers,
  handleSizeChange,
  handleCurrentChange,
  handleAdd: handleAddUser,
  handleEdit: handleEditUser,
  handleDelete,
  handleSubmit: handleSubmitUser,
  hasData,
  isEmpty
} = useTable<UserItem>({
  fetchApi: (params: any) => {
    // 添加搜索参数
    const searchParams = {
      ...params,
      search: searchQuery.value
    }
    return getUsersApi(searchParams)
  },
  createApi: createUserApi,
  updateApi: updateUserApi,
  deleteApi: deleteUserApi,
  pageSize: 15
})

// 使用表单验证 Composable
const { userFormRules, commonRules, createFormRules } = useFormRules()

// 密码重置相关
const passwordResetDialogVisible = ref(false)
const resetPasswordForm = reactive<ResetPasswordRequestData>({ password: '' })
const resetPasswordFormRef = ref<FormInstance>()
const userFormRef = ref<FormInstance>()

// 密码重置表单规则
const passwordResetRules = createFormRules({
  password: commonRules.password(6, 20)
})

// 搜索处理方法
const handleSearch = (query: string) => {
  searchQuery.value = query
  // 重置到第一页并刷新数据
  currentPage.value = 1
  fetchUsers(true) // 强制刷新，不使用缓存
}

const handleSearchClear = () => {
  searchQuery.value = ''
  // 重置到第一页并刷新数据
  currentPage.value = 1
  fetchUsers(true) // 强制刷新，不使用缓存
}

// 自定义新增用户方法
const handleAddUserCustom = () => {
  handleAddUser('新增用户')
  // 重置表单字段
  Object.assign(currentUser, { 
    username: '', 
    password: '', 
    email: '',
    roles: ['user'] 
  })
}

// 自定义编辑用户方法
const handleEditUserCustom = (row: UserItem) => {
  handleEditUser(row, '编辑用户')
}

// 删除用户
const handleDeleteUser = (id: string) => {
  handleDelete(id, '确定删除该用户吗？')
}

// 导出处理方法
const handleExport = (command: string) => {
  const exportData = userList.value.map(user => ({
    用户名: user.username,
    邮箱: user.email,
    角色: user.role,
    状态: user.status === 'active' ? '激活' : '禁用',
    创建时间: user.createdAt,
    最后登录: user.lastLogin || '从未登录'
  }))

  const config = {
    filename: `用户列表_${new Date().toISOString().split('T')[0]}`,
    headers: ['用户名', '邮箱', '角色', '状态', '创建时间', '最后登录'],
    dateFormat: 'YYYY-MM-DD HH:mm:ss'
  }

  switch (command) {
    case 'csv':
      exportToCSV(exportData, config)
      break
    case 'excel':
      exportToExcel(exportData, config)
      break
  }
}

const handleResetPassword = (row: UserItem) => {
  Object.assign(currentUser, row); // Store current user for password reset
  resetPasswordForm.password = '';
  passwordResetDialogVisible.value = true;
};

const submitResetPassword = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        await resetUserPasswordApi(currentUser.id!, resetPasswordForm);
        ElMessage.success('密码重置成功'); // Reverted to original success message
        passwordResetDialogVisible.value = false;
      } catch (error) {
        console.error('密码重置失败:', error);
        ElMessage.error('密码重置失败');
      }
    } else {
      console.log('表单校验失败', fields);
    }
  });
};

onMounted(() => {
  fetchUsers();
});

</script>

<template>
  <div class="user-management">
    <div class="header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <SearchInput
           v-model="searchQuery"
           placeholder="搜索用户名、邮箱或角色"
           :debounce-delay="300"
           show-search-button
           @search="handleSearch"
           @clear="handleSearchClear"
         />
         <div class="action-buttons">
           <el-dropdown @command="handleExport">
             <el-button :loading="isExporting" :icon="Download">
                导出数据
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
             <template #dropdown>
               <el-dropdown-menu>
                 <el-dropdown-item command="csv">导出为 CSV</el-dropdown-item>
                 <el-dropdown-item command="excel">导出为 Excel</el-dropdown-item>
               </el-dropdown-menu>
             </template>
           </el-dropdown>
           <el-button type="primary" @click="handleAddUserCustom">新增用户</el-button>
         </div>
      </div>
    </div>
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="email" label="邮箱" width="250" />
        <el-table-column prop="createdAt" label="创建时间" width="200">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="200">
          <template #default="scope">
            {{ formatDateTime(scope.row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="roles" label="角色" width="100">
          <template #default="scope">
            <el-tag v-for="role in scope.row.roles" :key="role" size="small">{{ role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-space>
              <el-button type="primary" size="small" :icon="'Edit'" @click="handleEditUserCustom(scope.row)">编辑</el-button>
              <el-button type="warning" size="small" :icon="'Refresh'" @click="handleResetPassword(scope.row)">重置密码</el-button>
              <el-button type="danger" size="small" :icon="'Delete'" @click="handleDeleteUser(scope.row.id)">删除</el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        show-info
        show-range
        show-size-changer
        show-quick-jumper
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="userFormRef?.resetFields()"
    >
      <el-form
        ref="userFormRef"
        :model="currentUser"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentUser.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input type="password" v-model="currentUser.password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitUser(userFormRef)">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog
      v-model="passwordResetDialogVisible"
      title="重置密码"
      width="400px"
      @close="resetPasswordFormRef?.resetFields()"
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="passwordResetRules"
        label-width="80px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input v-model="resetPasswordForm.password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordResetDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResetPassword(resetPasswordFormRef)">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.header-actions :deep(.search-input-container) {
  min-width: 300px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.el-card {
  border-radius: 8px;
}

.el-table {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 16px;
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: space-between;
  }
  
  .header-actions :deep(.search-input-container) {
    min-width: auto;
    flex: 1;
  }
}

@media (max-width: 480px) {
  .user-management {
    padding: 12px;
  }
  
  .header h2 {
    font-size: 20px;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>